/*******************************************************************************
 * Copyright (c) 2011 Gijs de Vries aka Janoz.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Gijs de Vries aka Janoz - initial API and implementation
 ******************************************************************************/
/* COPYRIGHT (C) 2008 Gijs de Vries. All Rights Reserved. */
package com.janoz.httpd.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.janoz.httpd.RequestHandler;
import com.janoz.httpd.Response;
import com.janoz.httpd.StatusCode;

/**
 * An implementation of the request handler to serve as a dispatcher
 * for other request handlers. Request handlers can be mapped on url
 * patterns.
 * 
 * @author Gijs de Vries
 *
 */
public class RequestDispatcher implements RequestHandler {

	
	private Map<String, RequestHandler> requestMapping = 
		new HashMap<String, RequestHandler>();
	private RequestHandler lastResort;

	/**
	 * @see com.janoz.httpd.RequestHandler#handleRequest(String, Properties)
	 * @param uri the uri of the request
	 * @param params the get parameters of the request
	 * @return The generated response that will be sent to the client
	 */
	public final Response handleRequest(String uri, Properties params) {
		for (String mapping : requestMapping.keySet()) {
			if (uri.matches(mapping)) {
				return requestMapping.get(mapping).handleRequest(uri, params);
			}
		}
		if (lastResort != null) {
			return lastResort.handleRequest(uri, params);
		} else {
			return Response.createEncodingSave(StatusCode.NOTFOUND);
		}
	}
	
	
	
	/**
	 * 
	 * @param mapping A regexp used to match the uri
	 * @param handler the handler to use when the mapping matches
	 */
	public final void addMapping(String mapping, RequestHandler handler) {
		requestMapping.put(mapping, handler);
	}
	
	/**
	 * 
	 * @param handler The handler that should be used when 
	 * nothing in the mapping matches the uri
	 */
	public final void setLastResort(RequestHandler handler) {
		lastResort = handler; 
	}
}
